package org.androidpn.server.dao.impl;

import java.util.List;

import javax.persistence.NoResultException;

import org.androidpn.server.dao.RoleDao;
import org.androidpn.server.entity.Role;
import org.springframework.stereotype.Repository;

/**
 * Dao 角色
 * 
 * @author 蔡琪
 * 
 */
@Repository("roleDao")
public class RoleDaoImpl extends BaseDaoImpl<Role, Long> implements RoleDao {

	public List<Role> getRolesByUserId(Long userId) {
		return entityManager
				.createQuery("from Role role where role.user.id=:userId",
						Role.class).setParameter("userId", userId)
				.getResultList();
	}

	public Role getRoleByNickname(String nickname) {
		if (nickname == null) {
			return null;
		}
		String jpql = "from Role role where lower(role.nickname)=lower(:nickname)";
		try {
			return entityManager.createQuery(jpql, Role.class)
					.setParameter("nickname", nickname).getSingleResult();

		} catch (NoResultException e) {
			return null;
		}

	}

	public boolean nicknameExist(String nickname) {
		if (nickname == null) {
			return false;
		}
		String jpql = "select count(*) from Role role where lower(role.nickname)=lower(:nickname)";
		Long count = entityManager.createQuery(jpql, Long.class)
				.setParameter("nickname", nickname).getSingleResult();
		return count > 0;
	}

	public List<Role> getRolesByUsername(String username) {
		String jpql = "from Role role where lower(role.user.username)=lower(:username)";
		List<Role> roles = entityManager.createQuery(jpql, Role.class)
				.setParameter("username", username).getResultList();
		return roles;
	}

	public Role getRoleByNicknamAndUsername(String nickname, String username) {
		String jpql = "from Role role where lower(role.nickname)=lower(:nickname) and lower(role.user.username)=lower(:username)";
		try {
			Role role = entityManager.createQuery(jpql, Role.class)
					.setParameter("nickname", nickname)
					.setParameter("username", username).getSingleResult();
			return role;
		} catch (Exception e) {
			return null;
		}
	}
}
